import type { UserConfig, ConfigEnv } from 'vite';
import { loadEnv } from 'vite';
import path from 'path';


import { createProxy, wrapperEnv, createVitePlugins } from './build/index';


export default ({ command, mode }: ConfigEnv): UserConfig => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  const viteEnv = wrapperEnv(env);
  const { VITE_PORT, VITE_PROXY, VITE_DROP_CONSOLE, VITE_PUBLIC_PATH } = wrapperEnv(env);

  const isBuild = command === 'build';
  
  return {
    root,
    base: VITE_PUBLIC_PATH,
    plugins: [...createVitePlugins(viteEnv,isBuild)],
    resolve: {
      alias: {
        'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js',
        '@': path.resolve(__dirname, 'src'),
        '/#/': path.resolve(__dirname, 'types'),
      },
    },
    server: {
      host: '0.0.0.0',
      port: VITE_PORT,
      proxy: createProxy(VITE_PROXY),
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
        },
      },
    },
    build: {
      minify: 'terser',
      target: 'es2015',
      outDir: 'dist',
      terserOptions: {
        compress: {
          keep_infinity: true,
          // Used to delete console in production environment
          drop_console: VITE_DROP_CONSOLE,
        },
      },
      chunkSizeWarningLimit: 2000,
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          },
        },
      },
    },
    // optimizeDeps: {
    //   include: ['ant-design-vue/es/locale/zh_CN', 'ant-design-vue/es/locale/en_US'],
    // },
  };
};
